package com.inlycat.web.intercepor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.inlycat.utils.Constant;
import com.inlycat.utils.redis.RedisClientTemplate;
/**
 * @author jarvan4dev@163.com
 * @since 2015年8月26日下午3:50:44
 * @category token拦截器
 *		每次拦截到token后判断是否有效，若无效则返回401状态码，客户端接收到401跳转到登录 
 **/

public class CheckTokenInterceptor extends HandlerInterceptorAdapter{

	@Resource
	private RedisClientTemplate redisClient;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object object) throws Exception {
		
		String token = request.getHeader("token");
		String userId = request.getHeader("userId");
		
		if(token==null||userId==null){
			response.setStatus(Constant.UN_AUTHENTICATION);
			return false;
		}
		if(token.equals(redisClient.get(userId))){
			/**
			 * 刷新token过期时间
			 */
			redisClient.expire(userId, Constant.TOKEN_EXPIRE_TIME);
			return true;
		}
		
		response.setStatus(Constant.UN_AUTHENTICATION);
		return false;
	}

}
